package kitrobot.com.bed.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import org.json.JSONArray;
import org.json.JSONObject;

import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import kitrobot.com.bed.Item;
import kitrobot.com.bed.PAdapter;
import kitrobot.com.bed.Service.DelepoService;
import kitrobot.com.bed.Service.GetbedService;
import kitrobot.com.bed.Service.IdentifyingService;
import kitrobot.com.bed.Service.PowerlistService;
import kitrobot.com.bed.fragment.FindFragment;
import kitrobot.com.wechat_bottom_navigation.R;

public class PowerdetailActivity extends AppCompatActivity implements View.OnClickListener {
    private ListView lv_pw;
    //定义控件
    String id=null;
    String token=null;
    private Button bt_pde;
    private CheckBox cb_all;
    private EditText et_search;
    private TextView tv_sp;
    //声明一个集合（数据源）
    private List<Item> data;
    //定义自定义适配器
    private PAdapter pAdapter;
    private String bid;
    private List<HashMap<String, Object>> bdata;
    private  String ptime="ptime";
    private String pname="pname";
    private String pphone="pphone";
    private String pid="pid";
    private String aid="aid";
    String cpid=null;
    String cptime=null;
    String cpname=null;
    String cpphone=null;
    String caid=null;
    String puphone=null;
    String puname=null;
    String puid=null;
    String paid=null;
    //给数据源添加数据
    /*private void initdata(){
        data=new ArrayList<>();
        for (int i=0;i<=10;i++){
            data.add(new Item("小明"+i,"110"+i,false));
        }
    }
    //返回数据给MyAdapter使用
    public  List<Item> getData(){
        return this.data;
    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.power_detail);
        lv_pw= (ListView) findViewById(R.id.lv_pw);
        tv_sp= (TextView) findViewById(R.id.tv_sp);
        //获取控件
        bt_pde= (Button) findViewById(R.id.bt_pde);
        et_search= (EditText) findViewById(R.id.et_search);
        Intent intent = getIntent();
        bid =  intent.getStringExtra("bid");
        SharedPreferences sp = getSharedPreferences("loginToken",
                Context.MODE_PRIVATE);
        id = sp.getString("id", "");
        token = sp.getString("token", "");

        //初始化数据源
        //initdata();
        //实例化自定义适配器，把listview传到自定义适配器中
        /*pAdapter =new PAdapter(this,lv_pw);
        //绑定适配器
        lv_pw.setAdapter(pAdapter);*/
        //初始化事件监听
        Listener();

    }
    public void Listener(){
        new Thread(){
            public void run(){
                final String result= PowerlistService.PowerlistByClientPost(bid,token);
                if (result!=null){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                //JSON字符串

                                //根据JSON字符串 获得JSON object对象
                                JSONObject jsonObject = new JSONObject(result);
                                //根据key 获取相应的value
                                String errno = jsonObject.getString("errno");
                                String errmsg="年龄:" + jsonObject.getString("errmsg");
                                JSONArray data = jsonObject.getJSONArray("data");


                                bdata = new ArrayList<HashMap<String, Object>>();
                                for (int i = 0; i < data.length(); i++) {
                                    HashMap<String, Object> mapItem = new HashMap<String, Object>();
                                    JSONObject jsonObject2 = (JSONObject) data.get(i);
                                    cptime = jsonObject2.getString("add_time");
                                    cpname = jsonObject2.getString("name");
                                    cpphone = jsonObject2.getString("phone");
                                    cpid = jsonObject2.getString("id");
                                    caid = jsonObject2.getString("appuser_id");
                                    mapItem.put(ptime, cptime);
                                    mapItem.put(pid, cpid);
                                    mapItem.put(aid, caid);
                                    mapItem.put(pname, cpname);
                                    mapItem.put(pphone,cpphone);
                                    bdata.add(mapItem);
                                }
                                SimpleAdapter simAdapter = new SimpleAdapter(
                                        PowerdetailActivity.this, bdata, R.layout.powerlist,
                                        new String[] { ptime, pname,pphone}, new int[] {
                                        R.id.tv_plti, R.id.tv_pln,R.id.tv_plt });
                                lv_pw.setAdapter(simAdapter);


                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    });
                }
                else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(PowerdetailActivity.this,"结果"+result,Toast.LENGTH_LONG).show();
                        }
                    });
                }
            };

        }.start();
        lv_pw.setOnItemClickListener(new itemClick());
    }

    class itemClick implements OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // TODO Auto-generated method stub
            Map<String, String> infoMap = (Map<String, String>) parent.getItemAtPosition(position);
            System.out.println(infoMap.get("pid"));
            System.out.println(infoMap.get("aid"));
            System.out.println(infoMap.get("pname"));
            System.out.println(infoMap.get("pphone"));
            puname=infoMap.get("pname");
            puphone=infoMap.get("pphone");
            puid=infoMap.get("pid");
            paid=infoMap.get("aid");
            tv_sp.setText(puname);
        }


    }
    public void Delepeo(View view){
        String check=tv_sp.getText().toString().trim();
        if (check.equals("请点击用户")){
            Toast.makeText(PowerdetailActivity.this, "请先选择一个用户！", Toast.LENGTH_SHORT).show();
        }
        else {
            new Thread() {
                public void run() {
                    final String result = DelepoService.DelepoByClientPost(puid, token);
                    if (result != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Toast.makeText(PowerdetailActivity.this, result, Toast.LENGTH_LONG).show();
                            }
                        });
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(PowerdetailActivity.this, "请求失败", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }

            }.start();
            Listener();
        }

    }

   /* private void initlistener() {
        /**
         * 全选复选框设置事件监听
         */
       /* cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (data.size()!=0) {//判断列表中是否有数据
                    if (isChecked) {
                        for (int i = 0; i < data.size(); i++) {
                            data.get(i).setChecked(true);
                        }
                        //通知适配器更新UI
                        pAdapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < data.size(); i++) {
                            data.get(i).setChecked(false);
                        }
                        //通知适配器更新UI
                        pAdapter.notifyDataSetChanged();
                    }
                }else{//若列表中没有数据则隐藏全选复选框
                    cb_all.setVisibility(View.GONE);
                }
            }
        });
        //删除按钮点击事件
        bt_pde.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建一个要删除内容的集合，不能直接在数据源data集合中直接进行操作，否则会报异常
                List<Item> deleSelect = new ArrayList<Item>();

                //把选中的条目要删除的条目放在deleSelect这个集合中
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getChecked()) {
                        deleSelect.add(data.get(i));
                    }
                }
                //判断用户是否选中要删除的数据及是否有数据
                if (deleSelect.size() != 0 && data.size() != 0) {
                    //从数据源data中删除数据
                    data.removeAll(deleSelect);
                    //把deleSelect集合中的数据清空
                    deleSelect.clear();
                    //把全选复选框设置为false
                    cb_all.setChecked(false);
                    //通知适配器更新UI
                    pAdapter.notifyDataSetChanged();
                } else if (data.size() == 0) {
                    Toast.makeText(PowerdetailActivity.this, "没有要删除的数据", Toast.LENGTH_SHORT).show();
                } else if (deleSelect.size() == 0) {
                    Toast.makeText(PowerdetailActivity.this, "请选中要删除的数据", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }*/

    public void Updateto(View view){
        String check=tv_sp.getText().toString().trim();
        if (check.equals("请点击用户")){
            Toast.makeText(PowerdetailActivity.this, "请先选择一个用户！", Toast.LENGTH_SHORT).show();
        }
       else {
            Intent intent = new Intent(this, UpdatepersonActivity.class);
            intent.putExtra("puid", puid);
            intent.putExtra("puphone", puphone);
            intent.putExtra("puname", puname);
            intent.putExtra("paid", paid);
            intent.putExtra("bid", bid);
            intent.putExtra("token", token);
            startActivityForResult(intent, 0);
        }
    }

    public void Addto(View view){
        Intent intent=new Intent(this,AddpersonActivity.class);
        intent.putExtra("bid", bid);
        intent.putExtra("token", token);
        startActivity(intent);
    }
    public void Caidan1(View view){
        Intent intent=new Intent(this,MainActivity.class);
        intent.putExtra("flag",1);
        startActivity(intent);
    }
    public void Caidan2(View view){
        Intent intent=new Intent(this,MainActivity.class);
        intent.putExtra("flag",2);
        startActivity(intent);
    }
    public void Caidan3(View view){
        Intent intent=new Intent(this,MainActivity.class);
        intent.putExtra("flag",3);
        startActivity(intent);
    }
    public void Caidan5(View view){
        Intent intent=new Intent(this,MainActivity.class);
        intent.putExtra("flag",4);
        startActivity(intent);
    }
    public void Finish(View view){
        finish();
    }
    @Override
    public void onClick(View view) {

    }
}
